package pro.jiug.files.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Controller
public class JiugController {

    @RequestMapping("/")
    public String toLogin(){
        return "index";
    }

    //图片服务器地址
    @Value("${jiug.system.file-path}")
    private String sysFilePath;
    //图片服务器地址
    @Value("${jiug.project.file-path}")
    private String proFilePath;

    @RequestMapping("api")
    @ResponseBody
    public JSONObject api( HttpServletRequest request) throws Exception{

        File file = new File(sysFilePath + "/icon.jpg");

        InputStream inputStream=new FileInputStream(file);

//        String path = ResourceUtils.getURL("classpath:").getPath() + proFilePath+ "/icon.jpg";
        String path = getUploadPath();
        OutputStream outputStream=new FileOutputStream( new File(path + File.separator + "icon.jpg"));

        byte[] buffer =new byte[1024*1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread=inputStream.read(buffer))!=-1)
        {
            bytesum+=byteread;
            outputStream.write(buffer,0,byteread);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();

        JSONObject resJson = new JSONObject();

        return resJson;
    }

//    @RequestMapping("api2")
//    public JSONObject uploadFile(@RequestParam("file") @ApiParam(value = "二进制文件流") MultipartFile file) {
//        String fileName = file.getOriginalFilename();//获取文件名
////        fileName = getFileName(fileName);
//        String filepath = getUploadPath();
//        if (!file.isEmpty()) {
//            try (BufferedOutputStream out = new BufferedOutputStream(
//                    new FileOutputStream(new File(filepath + File.separator + fileName)))) {
//                out.write(file.getBytes());
//                out.flush();
//                return new ResultModel<>(fileName);
//            } catch (FileNotFoundException e) {
//                return new ResultModel<>(false, "上传文件失败 FileNotFoundException：" + e.getMessage());
//            } catch (IOException e) {
//                return new ResultModel<>(false, "上传文件失败 IOException：" + e.getMessage());
//            }
//        } else {
//            return new ResultModel<>(false, "上传文件失败，文件为空");
//        }
//    }


    /**
     * 获取当前系统路径
     */
    private String getUploadPath() {
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (!path.exists()) path = new File("");
        File upload = new File(path.getAbsolutePath(), "static/uploadFile/");
        if (!upload.exists()) upload.mkdirs();
        return upload.getAbsolutePath();
    }

    /**
     * 文件名后缀前添加一个时间戳
     */
    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");  //设置时间格式
        String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
        fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        return fileName;
    }


    @RequestMapping("getFileMd5")
    @ResponseBody
    public void getFileMd5(HttpServletResponse response) throws Exception{//MultipartFile file

        File file = new File(sysFilePath + "/icon.jpg");

        InputStream inputStream=new FileInputStream(file);

        String fileMd5 = "";
        try {
            fileMd5 = DigestUtils.md5Hex(inputStream);
            System.out.println("md51"+fileMd5);
        } catch (IOException e) {

            e.printStackTrace();
        }



    }


    /**
     * excel 导入文件
     * @return
     * @throws IOException
     */
    @RequestMapping("/usermanager/excelImport.do")
    public String excelImport(
            MultipartFile multipartFile, HttpServletRequest request) throws IOException {

        String filename = multipartFile.getOriginalFilename();
        String path = request.getRealPath("u/cms/www/201509");
        InputStream fileInputStream=multipartFile.getInputStream();
        FileOutputStream fs=new FileOutputStream( path + "/"+ filename);
        System.out.println("------------"+path + "/"+ filename);
        byte[] buffer =new byte[1024*1024];
        int bytesum = 0;
        int byteread = 0;
        while ((byteread=fileInputStream.read(buffer))!=-1)
        {
            bytesum+=byteread;
            fs.write(buffer,0,byteread);
            fs.flush();
        }
        fs.close();
        fileInputStream.close();
        return "";
    }



}
